<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>检验任务详情</span>
          <div>
            <el-button type="primary" icon="Edit" @click="handleEdit" v-if="taskInfo.taskStatus == 1" v-hasPermi="['qep:inspection:task:edit']">编辑</el-button>
            <el-button icon="Back" @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <el-row :gutter="20" v-loading="loading">
        <el-col :span="24">
          <el-descriptions title="基本信息" :column="3" border>
            <el-descriptions-item label="任务编号">
              {{ taskInfo.taskCode || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="产品名称">
              {{ taskInfo.productName || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="批次号">
              {{ taskInfo.batchCode || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="工序名称">
              {{ taskInfo.processName || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="检验类型">
              {{ taskInfo.inspectionType || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="抽样数量">
              {{ taskInfo.sampleQuantity || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="任务状态">
              <el-tag :type="getTaskStatusType(taskInfo.taskStatus)">
                {{ getTaskStatusText(taskInfo.taskStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="计划日期">
              {{ parseTime(taskInfo.planDate) || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="实际日期">
              {{ parseTime(taskInfo.actualDate) || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="检验人员">
              {{ taskInfo.inspector || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="检验结论">
              <el-tag :type="getResultType(taskInfo.inspectionResult)">
                {{ taskInfo.inspectionResult || '-' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="优先级">
              <el-tag :type="getPriorityType(taskInfo.priority)">
                {{ getPriorityText(taskInfo.priority) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>

      <el-row style="margin-top: 20px;">
        <el-col :span="24">
          <el-descriptions title="时间信息" :column="2" border>
            <el-descriptions-item label="计划开始时间">
              {{ parseTime(taskInfo.planStartTime) || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="计划结束时间">
              {{ parseTime(taskInfo.planEndTime) || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="实际开始时间">
              {{ parseTime(taskInfo.actualStartTime) || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="实际结束时间">
              {{ parseTime(taskInfo.actualEndTime) || '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>

      <el-row style="margin-top: 20px;">
        <el-col :span="24">
          <el-descriptions title="其他信息" :column="1" border>
            <el-descriptions-item label="备注">
              {{ taskInfo.remark || '-' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>

      <el-divider content-position="center">检验数据</el-divider>

      <el-row>
        <el-col :span="24">
          <el-table v-loading="dataLoading" :data="dataList" border style="width: 100%">
            <el-table-column label="参数名称" align="center" prop="paramName" />
            <el-table-column label="标准值" align="center" prop="standardValue" />
            <el-table-column label="实测值" align="center" prop="measuredValue" />
            <el-table-column label="是否合格" align="center" prop="isQualified">
              <template #default="scope">
                <el-tag :type="scope.row.isQualified === 1 ? 'success' : 'danger'">
                  {{ scope.row.isQualified === 1 ? '合格' : '不合格' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="缺陷名称" align="center" prop="defectName" />
            <el-table-column label="操作" align="center" width="120">
              <template #default="scope">
                <el-button 
                  link type="primary" 
                  icon="View" 
                  @click="handleViewData(scope.row)"
                  v-hasPermi="['qep:inspection:data:query']"
                >查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <el-row style="margin-top: 20px;" v-if="taskInfo.taskStatus === 2">
        <el-col :span="24">
          <div class="action-buttons">
            <el-button type="primary" @click="handleAddData">
              <el-icon><Plus /></el-icon>
              添加检验数据
            </el-button>
            <el-button type="success" @click="handleImportData">
              <el-icon><Upload /></el-icon>
              导入检验数据
            </el-button>
            <el-button type="warning" @click="handleFinishTask">
              <el-icon><Check /></el-icon>
              完成检验任务
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 完成检验任务对话框 -->
    <el-dialog title="完成检验任务" v-model="finishOpen" width="500px" append-to-body>
      <el-form ref="finishForm" :model="finishForm" :rules="finishRules" label-width="100px">
        <el-form-item label="实际日期" prop="actualDate">
          <el-date-picker
            v-model="finishForm.actualDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="检验结论" prop="inspectionResult">
          <el-select v-model="finishForm.inspectionResult" placeholder="请选择检验结论">
            <el-option label="合格" value="合格" />
            <el-option label="不合格" value="不合格" />
            <el-option label="特采" value="特采" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFinishForm">确 定</el-button>
          <el-button @click="cancelFinish">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑检验任务对话框 -->
    <el-dialog title="编辑检验任务" v-model="editOpen" width="700px" append-to-body>
      <el-form ref="editForm" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务编号" prop="taskCode">
              <el-input v-model="form.taskCode" placeholder="自动生成" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <el-select v-model="form.productId" placeholder="请选择产品">
                <el-option
                  v-for="item in productOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="批次" prop="batchId">
              <el-select v-model="form.batchId" placeholder="请选择批次">
                <el-option
                  v-for="item in batchOptions"
                  :key="item.id"
                  :label="item.batchCode"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序" prop="processId">
              <el-select v-model="form.processId" placeholder="请选择工序">
                <el-option
                  v-for="item in processOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检验类型" prop="inspectionType">
              <el-input v-model="form.inspectionType" placeholder="请输入检验类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划日期" prop="planDate">
              <el-date-picker
                v-model="form.planDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="抽样数量" prop="sampleQuantity">
              <el-input-number v-model="form.sampleQuantity" :min="1" :max="1000" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级">
                <el-option label="低" value="1" />
                <el-option label="中" value="2" />
                <el-option label="高" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitEditForm">确 定</el-button>
          <el-button @click="cancelEdit">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { parseTime } from '@/utils/ruoyi';
import { getInspectionTask, updateInspectionTask, finishInspectionTask } from '@/api/qep/inspection/task';
import { listInspectionDataByTaskId } from '@/api/qep/inspection/data';
import { listProduct } from '@/api/qep/product';
import { listBatch } from '@/api/qep/production/batch';
import { listProcess } from '@/api/qep/process';

const route = useRoute();
const router = useRouter();
const taskId = ref(route.params.id);

// 任务信息
const taskInfo = ref({});
// 检验数据列表
const dataList = ref([]);
// 加载状态
const loading = ref(false);
// 数据加载状态
const dataLoading = ref(false);
// 是否显示完成弹出层
const finishOpen = ref(false);
// 是否显示编辑弹出层
const editOpen = ref(false);
// 产品选项
const productOptions = ref([]);
// 批次选项
const batchOptions = ref([]);
// 工序选项
const processOptions = ref([]);

// 完成表单参数
const finishForm = reactive({
  id: undefined,
  actualDate: undefined,
  inspectionResult: '合格'
});

// 完成表单校验
const finishRules = reactive({
  actualDate: [{ required: true, message: "请选择实际日期", trigger: "blur" }],
  inspectionResult: [{ required: true, message: "请选择检验结论", trigger: "blur" }]
});

// 编辑表单参数
const form = reactive({
  id: undefined,
  taskCode: undefined,
  productId: undefined,
  batchId: undefined,
  processId: undefined,
  inspectionType: undefined,
  planDate: undefined,
  sampleQuantity: 1,
  priority: '2',
  remark: undefined
});

// 表单校验
const rules = reactive({
  productId: [{ required: true, message: "请选择产品", trigger: "blur" }],
  batchId: [{ required: true, message: "请选择批次", trigger: "blur" }],
  processId: [{ required: true, message: "请选择工序", trigger: "blur" }],
  inspectionType: [{ required: true, message: "请输入检验类型", trigger: "blur" }],
  planDate: [{ required: true, message: "请选择计划日期", trigger: "blur" }],
  sampleQuantity: [{ required: true, message: "请输入抽样数量", trigger: "blur" }]
});

// 任务状态样式
const getTaskStatusType = (status) => {
  const numStatus = Number(status);
  if (numStatus == 1) return 'info';
  if (numStatus == 2) return 'warning';
  if (numStatus == 3) return 'success';
  return 'info';
};

// 任务状态文本
const getTaskStatusText = (status) => {
  const numStatus = Number(status);
  if (numStatus == 1) return '待检验';
  if (numStatus == 2) return '检验中';
  if (numStatus == 3) return '已完成';
  return '未知(' + status + ')';
};

// 检验结果样式
const getResultType = (result) => {
  if (result === '合格') return 'success';
  if (result === '不合格') return 'danger';
  if (result === '特采') return 'warning';
  return 'info';
};

// 优先级样式
const getPriorityType = (priority) => {
  if (priority === 1) return 'info';
  if (priority === 2) return 'warning';
  if (priority === 3) return 'danger';
  return 'info';
};

// 优先级文本
const getPriorityText = (priority) => {
  if (priority === 1) return '低';
  if (priority === 2) return '中';
  if (priority === 3) return '高';
  return '未知';
};

/** 查询任务详情 */
function getTaskDetail() {
  loading.value = true;
  getInspectionTask(taskId.value).then(response => {
    taskInfo.value = response.data;
    loading.value = false;
  });
}

/** 查询检验数据列表 */
function getDataList() {
  dataLoading.value = true;
  listInspectionDataByTaskId(taskId.value).then(response => {
    dataList.value = response.data;
    dataLoading.value = false;
  });
}

/** 返回按钮操作 */
function goBack() {
  router.go(-1);
}

/** 查看数据详情 */
function handleViewData(row) {
  router.push(`/inspection/data/detail/${row.id}`);
}

/** 添加检验数据 */
function handleAddData() {
  router.push(`/inspection/data/task/${taskId.value}`);
}

/** 导入检验数据 */
function handleImportData() {
  // 实现导入数据功能
}

/** 完成检验任务 */
function handleFinishTask() {
  resetFinishForm();
  finishForm.id = taskId.value;
  finishOpen.value = true;
}

/** 取消完成按钮 */
function cancelFinish() {
  finishOpen.value = false;
  resetFinishForm();
}

/** 完成表单重置 */
function resetFinishForm() {
  finishForm.id = taskId.value;
  finishForm.actualDate = new Date().toISOString().split('T')[0];
  finishForm.inspectionResult = '合格';
}

/** 提交完成表单 */
function submitFinishForm() {
  finishInspectionTask(finishForm).then(response => {
    ElMessage.success('检验任务完成成功');
    finishOpen.value = false;
    getTaskDetail();
  });
}

/** 编辑任务 */
function handleEdit() {
  // 加载下拉选项数据
  getProductList();
  getBatchList();
  getProcessList();
  
  // 复制任务数据到表单
  form.id = taskInfo.value.id;
  form.taskCode = taskInfo.value.taskCode;
  form.productId = taskInfo.value.productId;
  form.batchId = taskInfo.value.batchId;
  form.processId = taskInfo.value.processId;
  form.inspectionType = taskInfo.value.inspectionType;
  form.planDate = taskInfo.value.planDate;
  form.sampleQuantity = taskInfo.value.sampleQuantity;
  form.priority = taskInfo.value.priority;
  form.remark = taskInfo.value.remark;
  
  // 打开编辑对话框
  editOpen.value = true;
}

/** 取消编辑 */
function cancelEdit() {
  editOpen.value = false;
}

/** 提交编辑表单 */
function submitEditForm() {
  updateInspectionTask(form).then(response => {
    ElMessage.success('修改成功');
    editOpen.value = false;
    getTaskDetail();
  });
}

/** 查询产品列表 */
function getProductList() {
  listProduct().then(response => {
    productOptions.value = response.rows;
  });
}

/** 查询批次列表 */
function getBatchList() {
  listBatch().then(response => {
    batchOptions.value = response.rows;
  });
}

/** 查询工序列表 */
function getProcessList() {
  listProcess().then(response => {
    processOptions.value = response.rows;
  });
}

onMounted(() => {
  getTaskDetail();
  getDataList();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}
</style> 